﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Utils
{
	
	public class BinarySerializer
	{
		/// <summary>
		/// 二进制序列化
		/// </summary>
		/// <param name="data">需要转换的数据</param>
		/// <returns>byte数组</returns>
		public byte[] Serialize(object data)
		{
			if (data == null)
			{
				return new byte[0];
			}
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			byte[] result;
			using (MemoryStream memoryStream = new MemoryStream())
			{
				binaryFormatter.Serialize(memoryStream, data);
				byte[] objectDataAsStream = memoryStream.ToArray();
				result = objectDataAsStream;
			}
			return result;
		}
		/// <summary>
		/// 二进制反序列化
		/// </summary>
		/// <param name="data">需要转换的数据</param>
		/// <returns>字符串</returns>
		public object Deserialize(byte[] data)
		{
			if (data == null || data.Length==0)
			{
				return null;
			}
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			object result;
			using (MemoryStream memoryStream = new MemoryStream(data, 0, data.Length))
			{
				memoryStream.Seek(0L, SeekOrigin.Begin);
				object retObject = binaryFormatter.Deserialize(memoryStream);
				result = retObject;
			}
			return result;
		}		
	}
}
